#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : Wed Jul 10 2019
# @Author  : xujunfu (xjf891121@gmail.com})
# @Link    : http://junfuxu.github.io/
from datetime import datetime, timedelta

from .base import BaseHandler
from .gps_mongo import KYGPSMongoHandler


class GPSHandler(BaseHandler):

    def __init__(self, *args, **kwargs):
        self.last_post_time_map = {}
        self.gps_mongo_handler = KYGPSMongoHandler()
        return super().__init__(*args, **kwargs)

    def handle(self, msg):
        device_id = msg['deviceId']
        # 如果不在添加车辆的最后时间 同时向后端添加第一条数据
        license_number = self.imei2vehicle_info_map[device_id]['license_number']
        self.gps_mongo_handler.handle(msg, license_number)

        if device_id not in self.last_post_time_map:
            self.last_post_time_map[device_id] = datetime.now()

        # 每接近一分钟更新一次车辆状态
        if self.last_post_time_map[device_id] + timedelta(seconds=100) < datetime.now():
            data = {
                "status": "ONLINE",
                "latitude": float(msg['latitude']),
                "longitude": float(msg['longtitude']),
                "speed": self.transform_speed(msg['speed']),
                "last_time": self.timespan2str(msg['time'])
            }
            self.last_post_time_map[device_id] = datetime.now()
            vehicle_id = self.not_exist_add_vehicle(device_id)
            return self.yb_api.update_vehicle_status(vehicle_id, data)
